package servlet.action;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException,ServletException {
		loginAndRedirect(req,resp);
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException,ServletException {
		loginAndRedirect(req,resp);
	}
	
	private void loginAndRedirect(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException
	{
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        resp.setContentType("text/html");
        if (user != null) {
        	//check is user is present in our local database
        	if(checkApplicationDB(user.getEmail()))
        	{
        		RequestDispatcher fwd = req.getRequestDispatcher("/schoolHome.html");
        		 fwd.forward(req,resp);
        	}
        	else
        	{
        		resp.sendRedirect(userService.createLogoutURL("/error.html"));
        	}
           
        } else {
            resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
        }
	}
	
	private boolean checkApplicationDB(String emailID)
	{
		//get user with this email ID in DB
		//if not null put user object to custom session
		if(emailID.split("@")[0].equalsIgnoreCase("gokulvanan"))
		{
			return true;
		}
		else
			return false;
	}
}
